<template>
  <basic-container>

    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :permission="permissionList"
               :page.sync="page"
               :before-open="beforeOpen"
               @sortable-change="sortableChange"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter="filterChange"
               @sort-change="sortChange"
               @row-dblclick="handleRowDBLClick"               
               @on-load="onLoad">
      
      <template slot-scope="scope" slot="menuForm">
        <div  style="text-align:right; float:right">
          <el-button type="text"  v-if="operateType == 'edit'"   icon="el-icon-time" style="font-weight:normal;" size="large" @click.stop="getHistoryRecord">修改历史</el-button>
        </div> 
      </template>
      <template slot-scope="scope" slot="menuLeft">

        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.biz_model_task_item_batch_delete"
                   @click.stop="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menuRight">
        <el-button v-if="permission.biz_model_task_item_upload" type="default" @click.stop="openBatchAddDialog"  title="上传" icon="el-icon-upload" circle size="small"></el-button>
        <el-button v-if="permission.biz_model_task_item_download" type="default" @click.stop="exportExcel"  title="下载" icon="el-icon-download" circle size="small"></el-button>
      </template>
    </avue-crud>
    

    <!-- 批量导入数据 -->
    <upload-excel ref="uploadExcel" :actionUrl='actionUrl' ></upload-excel>
    <!-- 历史记录 -->
    <update-history ref="historyRecord"></update-history>
  </basic-container>
</template>

<script>
import {exportBizModelTaskItemExcel,saveOrUpdateBizModelTaskItem,saveOrUpdateBizModelTaskItemList,saveBizModelTaskItem,saveBizModelTaskItemList,deleteBizModelTaskItem,queryBizModelTaskItem,queryBizModelTaskItemListPage,updateBizModelTaskItem,deleteBizModelTaskItemList} from '@/api/biz/model/bizModelTaskItemApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
export default {
  data() {
    return {
      //批量导入
      actionUrl: '/biz/model/bizModelTaskItem/uploadExcel',

      //文件选择器的打开方式 add新增、edit修改、view 查看
      openType: 'edit',
      // 当前打开form对话框操作类型 
      operateType: 'add',

       
      
      importDataArea: '',
      batchAddDialog: false,
      form: {},
      currentRow: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 125,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addRowBtn:false,
        cellBtn:false,
        addBtn: true,
        viewBtn: true,
        delBtn: true,
        cancelBtn: true,
        printBtn:false,
        saveBtn: true,
        filterBtn:true,          
        menuWidth: 200,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        sortable: true,
        column: [
          {
            label: '操作名称',
            prop: 'handleName', 
            type: 'select', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 12,
            sortable: false,
            hide: false,
            width: 300,
            maxlength: 50,
            overHidden: true,
            cell: true,
            value: '检查',
            rules: [{
              message: '请输入操作名称',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 50,
              message: '内容长度不能超过50字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '业务实体名称',
            prop: 'bizEntityName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 50,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入业务实体名称',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 50,
              message: '内容长度不能超过50字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '判断条件',
            prop: 'judgeCondition', 
            type: 'textarea', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 500,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入判断条件',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 500,
              message: '内容长度不能超过500字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '变更属性值',
            prop: 'changeAttributeValue', 
            type: 'textarea', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 2000,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入变更属性值',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 2000,
              message: '内容长度不能超过2000字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '公共规则',
            prop: 'publicRuleGroup', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 24,
            sortable: false,
            hide: false,
            maxlength: 2000,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入公共规则组',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 2000,
              message: '内容长度不能超过2000字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '核算规则',
            prop: 'accountingRuleGroup', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 24,
            sortable: false,
            hide: false,
            maxlength: 2000,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入核算规则组',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 2000,
              message: '内容长度不能超过2000字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '特有规则',
            prop: 'specificRuleGroup', 
            type: 'textarea', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true, 
            span: 24,
            sortable: false,
            hide: false,
            maxlength: 2000,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入特有规则组',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 2000,
              message: '内容长度不能超过2000字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          
          {
            label: '需求条目',
            prop: 'demandItemName', 
            type: 'textarea', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 24,
            sortable: false,
            hide: true,
            maxlength: 50,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入需求条目名称',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 50,
              message: '内容长度不能超过50字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '任务执行条件',
            prop: 'taskExecPremiseCondition', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 12,
            sortable: false,
            hide: true,
            maxlength: 500,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入任务执行前提条件',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 500,
              message: '内容长度不能超过500字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '任务执行角色',
            prop: 'taskExecRoleName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 50,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入任务执行角色名称',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 50,
              message: '内容长度不能超过50字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '任务输入',
            prop: 'taskInputGroup', 
            type: 'textarea', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 12,
            sortable: false,
            hide: true,
            maxlength: 2000,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入任务输入组',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 2000,
              message: '内容长度不能超过2000字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '任务输出',
            prop: 'taskOutputGroup', 
            type: 'textarea', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 12,
            sortable: false,
            hide: true,
            maxlength: 2000,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入任务输出组',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 2000,
              message: '内容长度不能超过2000字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '所属需求章节',
            prop: 'belongDemandChapterName', 
            type: 'textarea', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 24,
            sortable: false,
            hide: true,
            maxlength: 50,
            overHidden: true,
            width: 300,
            cell: true,
            rules: [{
              message: '请输入所属需求章节名称',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 50,
              message: '内容长度不能超过50字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '所属领域中心',
            prop: 'belongDomainCenterName', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 12,
            sortable: false,
            hide: true,
            maxlength: 50,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入所属领域中心名称',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 50,
              message: '内容长度不能超过50字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '所属产品组件',
            prop: 'belongProductComponent', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            filterable: true,
            span: 12,
            sortable: false,
            hide: true,
            maxlength: 100,
            overHidden: true,
            cell: true,
            width: 300,
            rules: [{
              message: '请输入所属产品组件',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 100,
              message: '内容长度不能超过100字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
        ]
      },
      data: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: [],
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','orgTree','genOrgTree','userInfo','permission','projectInfo']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.biz_model_task_item_add, false),
        viewBtn: this.vaildData(this.permission.biz_model_task_item_view, false),
        delBtn: this.vaildData(this.permission.biz_model_task_item_delete, false),
        editBtn: this.vaildData(this.permission.biz_model_task_item_edit, false),
        printBtn: this.vaildData(this.permission.biz_model_task_item_print, false),
        searchBtn:this.vaildData(this.permission.biz_model_task_item_search, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: {
    /**
     * 启动流程
     */
    startFlow(row){
      this.currentRow = row;
      //flowOptFlag 1-开始启动 2-处理流程
      this.flowArea.isFlow = this.isFlow;
      this.flowArea.flowOptFlag = '1';
      this.processFlow();
    },
    /**
     * 启动流程，执行流程方法
     */
    processFlow(){
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
      });
      this.reqParams.flowArea = this.flowArea
      this.reqParams.singleBody = this.currentRow;
      this.commonData = reqCommonMsg(this.reqParams)
      updateBizModelTaskItem(this.commonData).then(() => {
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
        loading.close();
      }, error => {
        window.z(error); 
        loading.close();
      });
    },
    /**
     * 加载列表数据
     */
    onLoad(page) {
   	  //如果和项目相关，请打开项目ID作为查询条件
      //if(!this.$project.checkChooseProject()){
      //  return false;
      //}
      //this.singleBody.projectId = this.projectInfo.id;
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryBizModelTaskItemListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      let formatUser = {};
      this.commonData = reqCommonMsg(this.reqParams)
      saveBizModelTaskItem(this.commonData).then(() => {
        done();
        this.singleBody={};
        //this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        this.$console.log(error);
        done();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) {
      this.reqParams.singleBody = row;
      let formatUser = {};
      this.commonData = reqCommonMsg(this.reqParams)
      updateBizModelTaskItem(this.commonData).then(() => {
        done();
        this.singleBody={}
        //this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        this.$console.log(error);
        done();
      });
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteBizModelTaskItem(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      if(this.permission.biz_model_task_item_dbclick){
        this.$refs.crud.rowView(row,row.$index);
      }
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      this.$refs.uploadExcel.openUploadDialog();
    },
    /**
     * 批量导入
     */
    handleImport() {
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading',
      });
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        lineList.forEach((element,index) => {
          if(element.trim() != ''){
            var field = element.split('\t')
            var fieldList = {
              handleName:field[0].trim(),
              bizEntityName:field[1].trim(),
              judgeCondition:field[2].trim(),
              changeAttributeValue:field[3].trim(),
              publicRuleGroup:field[4].trim(),
              specificRuleGroup:field[5].trim(),
              accountingRuleGroup:field[6].trim(),
              demandItemName:field[7].trim(),
              taskExecPremiseCondition:field[8].trim(),
              taskExecRoleName:field[9].trim(),
              taskInputGroup:field[10].trim(),
              taskOutputGroup:field[11].trim(),
              belongDemandChapterName:field[12].trim(),
              belongDomainCenterName:field[13].trim(),
              belongProductComponent:field[14].trim(),
            }
            dataList[index] = fieldList
            //this.$console.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveBizModelTaskItemList(this.commonData).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
        }, error => {
          this.$console.log(error);
          loading.close();
        });      
      }
      else{
        this.loading=false;
        this.$message({
          type: 'warning',
          message: '数据格式不正确!'
        });
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteBizModelTaskItemList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let copyValue=row;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.tableName='拷贝 '+ copyValue.tableName; 
        this.reqParams.singleBody = copyValue;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysToolTables(this.commonData).then(() => {
          this.singleBody={};
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.loading=false;
        }, error => {
          this.$console.log(error);
          this.loading=false;
        });
      }).catch(() => {});       
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        this.operateType = 'edit';
        this.reqParams =  {
          singleBody: {
            id:this.form.id
          }
        }
        let commonData = reqCommonMsg(this.reqParams)
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading'
        });
        queryBizModelTaskItem(commonData).then(res => {
          this.form = res.data.body.singleBody;
          loading.close();
          done();
        }, error => {
          this.$console.log(error);
          loading.close();
          done();
        });
      }
      if (['add'].includes(type)) {
        this.operateType = 'add';
        done();
      }
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      // this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportBizModelTaskItemExcel(this.commonData);
    },
    /**
     * 获取业务字典参数
     */
    async getBizDict() {
      let dicData = await this.$params.getBizDict('["handleName"]');
      this.findObject(this.option.column, 'handleName').dicData = dicData.handleName;
    },
    
    /**
     * 调用子组件方法查询历史
     */
    getHistoryRecord () {
      setTimeout(() => {
        this.$refs.historyRecord.getUpdateHistoryRecord(this.form.id);
      })
    },
  },
  created() {
    
    this.showColumn = this.$getStore({name: this.userInfo.userId+'bizModelTaskItemColumn'});
    //获取业务字典
    setTimeout(() => {
      this.getBizDict();
    }, 1000);
    
    //加载机构
    let getOrgTreeTimer = setInterval(() => {
      if(this.genOrgTree){
        let orgTree = [];
        this.genOrgTree.forEach(element => {
          if(element.orgType == '1'){
            orgTree.push(element);
          }
        });
        clearInterval(getOrgTreeTimer);
      }
    }, 100);
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name: this.userInfo.userId+'bizModelTaskItemColumn', content: this.showColumn});
      },
      deep: true
    }
  }
};
</script>
